package com.village.friend.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.village.friend.constant.MsgCodeEnum;
import com.village.friend.dto.request.*;
import com.village.friend.dto.response.*;
import com.village.friend.entity.*;
import com.village.friend.mapper.UserAuthMapper;
import com.village.friend.mapper.UserHeartMapper;
import com.village.friend.mapper.UserMapper;
import com.village.friend.service.AppInviteService;
import com.village.friend.service.AppUserAccountService;
import com.village.friend.service.AppUserMappingService;
import com.village.friend.service.UserService;
import com.village.friend.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Value("${header.boy}")
    private String headerBoy;
    @Value("${header.girl}")
    private String headerGirl;

    @Autowired
    UserHeartMapper userHeartMapper;

    @Autowired
    UserAuthMapper authCodeMapper;

    @Autowired
    AppInviteService inviteService;

    @Autowired
    AppUserMappingService mappingService;

    @Autowired
    AppUserAccountService accountService;




    @Override
    public User findByInviteCode(String inviteCode) {
        if (StringUtils.isEmpty(inviteCode)) {
            return null;
        }
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("invite_code", inviteCode);
        return baseMapper.selectOne(qw);
    }



    @Override
    public BaseResponse<User> getUserMsg(GetUserDto param) {
        String usernameP = param.getUsername();
        User userEntity = findByUsername(usernameP);
        return new BaseResponse(MsgCodeEnum.SUCCESS, userEntity);
    }

    @Override
    public BaseResponse<UserResDto> updateUserMsg(UpdateUserDto param) {
        if (StringUtils.isBlank(param.getUsername())) {
            return BaseResponse.paramsError("username不能为空!!");
        }
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", param.getUsername());
        User orgUser = baseMapper.selectOne(qw);
        if (orgUser == null) {
            return BaseResponse.paramsError("用户不存在!!");
        }
        User parent = null;
        if (StringUtils.isNotBlank(param.getInviteCode())) {
            if (StringUtils.isNotBlank(orgUser.getParent())) {
                return BaseResponse.paramsError("用户已经有上级了,不能设置上级邀请码!!");
            }
            parent = findByInviteCode(param.getInviteCode());
            if (parent == null) {
                return BaseResponse.paramsError("邀请码对应的上级用户不存在!!!");
            }
            //添加关系映射
            addUserMapping(orgUser, parent);
        }
        User user = ParamUtils.update2User(param);
        if (parent != null) {
            user.setParent(parent.getUsername());
        }
        baseMapper.update(user, qw);
//        baseMapper.updateByUsername(param.getUsername(), param.getAvatarurl(), param.getBirth(), param.getHeight(), param.getWeight(), ParamUtils.toJSONString(param.getPhotos()), param.getIsHide(), null, param.getIsLogout(), null, param.getCity(), param.getSelfDesc(), param.getProfession(), param.getSalaryYear(), param.getWeChatAccount(), ParamUtils.toString(param.getAboutPlay()), ParamUtils.toString(param.getAboutMe()), ParamUtils.toString(param.getAboutLove()));
        User userEntity = findByUsername(param.getUsername());
        return new BaseResponse(MsgCodeEnum.SUCCESS, ParamUtils.userToUserResDto(userEntity));
    }

    @Override
    public BaseResponse<Object> heart(HeartDto param) {
        userHeartMapper.add(param.getUsername(), param.getIp(), param.getLatitude(), param.getLongitude());
        return new BaseResponse(MsgCodeEnum.SUCCESS, null);
    }

    @Override
    public BaseResponse<KeyWordsResDto> keyWords(KeyWordsDto param) {
        String aboutPlay = "活地图,攻略王,会游泳,不抽烟,男友力,负责吃,自来熟";
        String aboutMe = "女汉子,傻白甜,拖延症,有趣灵魂,双重人格,文艺青年,安静,霸道总裁,大叔控,小萝莉";
        String aboutLove = "相对保守,开放,拒绝婚前,跟着感觉走,两情相悦";

        KeyWordsResDto data = new KeyWordsResDto();
        data.setAboutPlay(JSONObject.parseObject(JSON.toJSONString(StringUtils.split(aboutPlay, ",")), ArrayList.class));
        data.setAboutMe(JSONObject.parseObject(JSON.toJSONString(StringUtils.split(aboutMe, ",")), ArrayList.class));
        data.setAboutLove(JSONObject.parseObject(JSON.toJSONString(StringUtils.split(aboutLove, ",")), ArrayList.class));
        return new BaseResponse(MsgCodeEnum.SUCCESS, data);
    }

    @Override
    public List<User> listIn(Collection<String> usernames) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.in("username",usernames);
        return baseMapper.selectList(qw);
    }

    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", username);
        return baseMapper.selectOne(qw);
    }

    public User findByPhone(String phone) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone", phone);
        return baseMapper.selectOne(qw);
    }

    @Override
    public User findParentByLevel(String username, Integer level) {
        return baseMapper.findParentByLevel(username, level);
    }

    @Override
    public BaseResponse<IPage<User>> page(UserPageDto param) {
        IPage<User> page = new Page<>(param.getPage(), param.getLimit());
        QueryWrapper<User> ew = new QueryWrapper<>();

        if(StringUtils.isNotEmpty(param.getPhone())){
            ew.eq("phone",param.getPhone());
        }
        if(StringUtils.isNotEmpty(param.getUsername())){
            ew.eq("username",param.getUsername());
        }
        if(StringUtils.isNotEmpty(param.getNickname())){
            ew.like("nickname", param.getNickname());
        }

        ParamUtils.fullTime(param,ew);
        ew.orderByDesc("create_time");
        page = super.page(page, ew);
        return BaseResponse.success(page);
    }

    /**
     * 插入用户关系
     *
     * @param user
     * @param parent
     */
    private void addUserMapping(User user, User parent) {
        if (parent != null) {
            mappingService.insertUserMapping(user.getUsername(), parent.getUsername());
        }

    }


    /**
     * 添加用户钱包
     *
     * @param user
     */
    private void addUserAccount(User user) {
        AppUserAccount account = new AppUserAccount();
        account.setId(InviteUtils.get32UUID());
        account.setUserId(user.getUsername());
        accountService.save(account);
    }
}
